package com.example.houseman.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.houseman.entity.TSfContract;
import com.example.houseman.enums.AccountTypeEnum;
import com.example.houseman.enums.CertificateType;
import com.example.houseman.enums.OwnershipTypeEnum;
import com.example.houseman.enums.TenantManage;
import com.example.houseman.service.ITSfContractService;
import com.example.houseman.service.ITSfFinalStatementDetailService;
import com.example.houseman.service.ITSfTerminationService;
import com.github.pagehelper.PageInfo;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.org.dto.*;
import com.org.util.PayMentPlanGenerator;
import com.org.vo.ResultEntity;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 龚梦
 * @since 2021-04-02
 */
@RestController
@RequestMapping("/hou/TSfContractController")
public class TSfContractController {
    @Autowired
    ITSfContractService itSfContractService;

    @Autowired
    ITSfTerminationService itSfTerminationService;

    @Autowired
    ITSfFinalStatementDetailService itSfFinalStatementDetailService;

    //收房列表查询
    @RequestMapping("list")
    public ResultEntity list(TsfContractDto tsfContractDto) {

        PageInfo<TSfContract> list = itSfContractService.getlist(tsfContractDto);
        System.out.print(list);
        return ResultEntity.ok("200", "成功", list);

    }

    //业主列表查询
    @RequestMapping("yezhulist")
    public ResultEntity yezhulist(TsfContractDto tsfContractDto) {

        PageInfo<TSfContract> list = itSfContractService.getlists(tsfContractDto);

        return ResultEntity.ok("200", "成功", list);

    }

    //解约列表查询
    @RequestMapping("jie")
    public ResultEntity jie(TsfContractDto tsfContractDto) {
        PageInfo<TSfContract> ss = itSfContractService.jie(tsfContractDto);
        return ResultEntity.ok("200", "成功", ss);
    }

    //解约中的收房合同回显
    @RequestMapping("getOne")
    public TSfContract getOne(Long id) {
        System.out.println(id + "======");
        TSfContract tSfContract = itSfContractService.getById(id);
        return tSfContract;
    }

    @RequestMapping("add")
    public boolean add(@RequestBody TSfContract tSfContract) {
        try {
            itSfContractService.save(tSfContract);
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    @RequestMapping("selectlist")
    public ResultEntity contractlist(@RequestBody TsfContractDto contractDto) {
        PageInfo<TSfContract> page = itSfContractService.selectList(contractDto);
        return ResultEntity.ok("200", "查询", page);
    }

    @RequestMapping("updateStatus")
    public ResultEntity upadateStatus(@RequestBody TsfContractDto contractDto) {
        itSfContractService.updateStatus(contractDto);
        return ResultEntity.ok("修改成功");
    }

    /**
     * 获取所有权类型
     *
     * @return
     */
    @RequestMapping("/houseAllTypeEnum")
    public ResultEntity houseAllTypeEnum() {
        return ResultEntity.ok("200", "查询所有权类型成功", OwnershipTypeEnum.values());
    }


    /**
     * 获取所有的身份证类型
     *
     * @return
     */
    @RequestMapping("/certificateType")
    public ResultEntity certificateType() {
        return ResultEntity.ok("200", "查询身份证类型成功", CertificateType.values());
    }

    /**
     * 获取所有租房类型类型
     *
     * @return
     */
    @RequestMapping("/tenantManageEnum")
    public ResultEntity tenantManageEnum() {
        return ResultEntity.ok("200", "查询类型成功", TenantManage.values());
    }

    /**
     * 获取公私账户
     *
     * @return
     */
    @RequestMapping("/accountTypeEnum")
    public ResultEntity accountTypeEnum() {
        return ResultEntity.ok("200", "查询类型成功", AccountTypeEnum.values());
    }

    /**
     * 收房合同录入：下一步 校验合同租约信息等
     */
    @RequestMapping("nextSfContract")
    @ResponseBody
    private ResultEntity nextCfContract(SaveSfContractForm saveSfContractForm) {
        return ResultEntity.ok();
    }

    @RequestMapping("saveSfContract")
    private ResultEntity saveSfContract(@RequestBody SaveSfContractForm saveSfContractForm)
            throws Exception {
        RequestDetailSfContractSaveDto requestDetailSfContractSaveDto = new RequestDetailSfContractSaveDto();
        BeanUtils.copyProperties(saveSfContractForm, requestDetailSfContractSaveDto);
        requestDetailSfContractSaveDto.setDepositMoney(new BigDecimal(saveSfContractForm.getDepositMoney()));
        requestDetailSfContractSaveDto.setMonthRent(new BigDecimal(saveSfContractForm.getMonthRent()));
        requestDetailSfContractSaveDto.setHouseName(saveSfContractForm.getHouseInfo());
        requestDetailSfContractSaveDto.setLesaseStartTime(saveSfContractForm.getStartDate());
        requestDetailSfContractSaveDto.setLeaseEndTime(saveSfContractForm.getEndDate());
        itSfContractService.saveSfContract(requestDetailSfContractSaveDto);
        return ResultEntity.ok();
    }

    /**
     * 根据合同租约信息生成相应账期的付款计划信息
     *
     * @param saveSfContractForm
     * @return
     * @throws ParseException
     */
    @RequestMapping("generatePayMentPlan")
    @ResponseBody
    private Object generatePayMentPlan(@RequestBody SaveSfContractForm saveSfContractForm) throws ParseException {
        Map<String, Object> map = new HashMap<>();
        // 计算生成各账期付款计划
        CalculateFkPlanForm dataPlan = new CalculateFkPlanForm();
        BeanUtils.copyProperties(saveSfContractForm, dataPlan);
        // 收房月租金
        dataPlan.setMonthRent(new BigDecimal(saveSfContractForm.getMonthRent()));
        // 房产押金
        dataPlan.setDepositMoney(new BigDecimal(saveSfContractForm.getDepositMoney()));
        List<CwPaymentPlanDto> payMentPlanList = PayMentPlanGenerator.generatePayMentPlan(dataPlan);

        map.put("payMentPlanList", payMentPlanList);
        BigDecimal totalDeposit = new BigDecimal(saveSfContractForm.getDepositMoney())
                .multiply(new BigDecimal(saveSfContractForm.getDepositType()));
        if (BigDecimal.ZERO.equals(totalDeposit)) {
            // 无押金
            map.put("hasDeposit", 0);
        } else {
            // 有押金
            map.put("hasDeposit", 1);
        }
        if (null != saveSfContractForm.getLastContractId()) {
            map.put("isXuYue", 1);// 续约(续约时自动生成的是已付的付款单，支付状态不可编辑)
        } else {
            map.put("isXuYue", 0);
        }
        // 合同总金额
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (CwPaymentPlanDto cwPaymentPlanDto : payMentPlanList) {
            totalAmount = totalAmount.add(cwPaymentPlanDto.getPaymentAmount());
        }

        map.put("totalAmount", totalAmount);
        map.put("totalDeposit", totalDeposit);
        map.put("preCycleChange", 0);
        return map;
    }

    @RequestMapping("getContractByHouseId")
    public ResultEntity getContractByHouseId(String houseId){
        QueryWrapper<TSfContract> tSfContractQueryWrapper = new QueryWrapper<>();
        tSfContractQueryWrapper.eq("house_id",houseId);
        List<TSfContract> list = itSfContractService.list(tSfContractQueryWrapper);
        return ResultEntity.ok(list.get(list.size()-1));
    }

    @RequestMapping("extensionSfContract")
    public ResultEntity extensionContract(@RequestBody SaveSfContractForm saveSfContractForm){
        //根据houseId查询上一份合同id
        QueryWrapper<TSfContract> tSfContractQueryWrapper = new QueryWrapper<>();
        tSfContractQueryWrapper.eq("house_id",saveSfContractForm.getHouseId());
        tSfContractQueryWrapper.orderByAsc("update_time");

        List<TSfContract> list = itSfContractService.list(tSfContractQueryWrapper);

        TSfContract tSfContract = list.get(list.size() - 1);
        RequestDetailSfContractSaveDto requestDetailSfContractSaveDto = new RequestDetailSfContractSaveDto();
        BeanUtils.copyProperties(saveSfContractForm, requestDetailSfContractSaveDto);
        requestDetailSfContractSaveDto.setLastContractId(tSfContract.getId());
        requestDetailSfContractSaveDto.setDepositMoney(new BigDecimal(saveSfContractForm.getDepositMoney()));
        requestDetailSfContractSaveDto.setMonthRent(new BigDecimal(saveSfContractForm.getMonthRent()));
        requestDetailSfContractSaveDto.setHouseName(saveSfContractForm.getHouseInfo());
        requestDetailSfContractSaveDto.setLesaseStartTime(saveSfContractForm.getStartDate());
        requestDetailSfContractSaveDto.setLeaseEndTime(saveSfContractForm.getEndDate());
        itSfContractService.extensionSfContract(requestDetailSfContractSaveDto);
        return ResultEntity.ok();
    }

    @RequestMapping("getContractPDF")
    public void getContractPDF(String contractNo, HttpServletResponse response) throws IOException {
        String model = "https://ysyfiles.oss-cn-beijing.aliyuncs.com/pdf/contract.pdf?versionId=CAEQHhiBgMDW_O_T6hciIDRmMTA5YTU1ZWNhMzQwNjc4NzYzNDRmNzViZjQyOGE5";
        String contractSrc = "E:\\img\\contracts\\";
        //数据封装
        Map<String, Object> sourceMap = new HashMap<>();
        QueryWrapper<TSfContract> tSfContractQueryWrapper = new QueryWrapper<>();
        tSfContractQueryWrapper.eq("sf_contract_no",contractNo);
        TSfContract one = itSfContractService.getOne(tSfContractQueryWrapper);
        sourceMap.put("permise_name",one.getPremiseName());
        sourceMap.put("house_name",one.getHouseName());
        sourceMap.put("contractNo",contractNo);
        sourceMap.put("sign_user_name",one.getSignUserName());
        sourceMap.put("sf_user_name",one.getSfUserName());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        sourceMap.put("lease_start_time",simpleDateFormat.format(one.getLeaseStartTime()));
        sourceMap.put("lease_end_time",simpleDateFormat.format(one.getLeaseEndTime()));
        HashMap<String, Object> toPDF = new HashMap<>();

        HashMap<String, Object> imageMap = new HashMap<>();
        imageMap.put("img","E:\\img\\zhang.png");
        toPDF.put("model",model);
        toPDF.put("contractSrc",contractSrc+contractNo+".pdf");
        toPDF.put("dataMap",sourceMap);
        toPDF.put("imageMap",imageMap);
        pdfout(toPDF);
    }

    public static void pdfout(Map<String,Object> sourceMap) {
        PdfReader reader;
        FileOutputStream out;
        ByteArrayOutputStream bos;
        PdfStamper stamper;
        try {
            // 设置字体
            BaseFont bf = BaseFont.createFont("C:\\Windows\\Fonts\\Deng.ttf" , BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            Font fontChinese = new Font(bf, 3, Font.NORMAL);
            // 输出流
            out = new FileOutputStream((String) sourceMap.get("contractSrc"));
            // 读取pdf模板
            reader = new PdfReader((String) sourceMap.get("model"));
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();

            //文字类的内容处理
            Map<String,String> dataMap = (Map<String,String>)sourceMap.get("dataMap");
            form.addSubstitutionFont(bf);
            for(String key : dataMap.keySet()){
                String value = dataMap.get(key);
                form.setField(key,value);
            }

            //图片类的内容处理
            Map<String,Object> imageMap = (Map<String,Object>)sourceMap.get("imageMap");
            for(String key : imageMap.keySet()) {
                String imgpath = imageMap.get(key).toString();
                int pageNo = form.getFieldPositions(key).get(0).page;
                Rectangle signRect = form.getFieldPositions(key).get(0).position;
                float x = signRect.getLeft();
                float y = signRect.getBottom();
                //根据路径读取图片
                Image image = Image.getInstance(imgpath);
                //获取图片页面
                PdfContentByte under = stamper.getOverContent(pageNo);
                //图片大小自适应
                image.scaleToFit(signRect.getWidth(), signRect.getHeight());
                //添加图片
                image.setAbsolutePosition(x, y);
                under.addImage(image);
            }
            // 如果为false，生成的PDF文件可以编辑，如果为true，生成的PDF文件不可以编辑
            stamper.setFormFlattening(true);
            stamper.close();
            Document doc = new Document();
            Font font = new Font(bf, 32);
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
            copy.addPage(importPage);
            doc.close();


        } catch (IOException | DocumentException e) {
            System.out.println(e);
        }
    }
}
